package json;

import bean.Diaosi;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JsonObjectSample {

    public static void main(String[] args) {
        createJsonByBean();

    }

//    {
//        "name" : "王小二",
//            "age" : 25.2,
//            "birthday" : "1990-01-01",
//            "school" : "蓝翔",
//            "major" : ["理发","挖掘机"],
//        "has_girlfriend" : false,
//            "car" : null,
//            "house" : null,
//            "comment" : "这是一个注释"
//    }

//        json在线格式化工具
//    http://www.kjson.com/jsoneditor/
    private static void jsonObject() {
        JSONObject wangxiaoer = new JSONObject();
        Object nullObj = null;

        try {
            wangxiaoer.put("name","王小二");
            wangxiaoer.put("age",25.2);
            wangxiaoer.put("birthday","1990-01-01");
            wangxiaoer.put("school","蓝翔");
            wangxiaoer.put("major",new String[]{"理发","挖掘机"});
            wangxiaoer.put("has_girlfriend",false);
            wangxiaoer.put("car",nullObj);
            wangxiaoer.put("house",nullObj);
            wangxiaoer.put("comment","这是一个注释");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //print
        System.out.println(wangxiaoer.toString());
    }

    private static void createJsonByMap(){
        Map<String,Object> wangxiaoer = new HashMap<String,Object>();
        Object nullObj = null;
        wangxiaoer.put("name","王小二");
        wangxiaoer.put("age",25.2);
        wangxiaoer.put("birthday","1990-01-01");
        wangxiaoer.put("school","蓝翔");
        wangxiaoer.put("major",new String[]{"理发","挖掘机"});
        wangxiaoer.put("has_girlfriend",false);
        wangxiaoer.put("car",nullObj);
        wangxiaoer.put("house",nullObj);
        wangxiaoer.put("comment","这是一个注释");
        //print
        System.out.println(new JSONObject(wangxiaoer).toString());
    }

    private static void createJsonByBean(){
        Diaosi wangxiaoer = new Diaosi();
        wangxiaoer.setName("王小二");
        wangxiaoer.setAge(25.2);
        wangxiaoer.setBirthday("1990-01-01");
        wangxiaoer.setSchool("蓝翔");
        wangxiaoer.setMajor(new String[]{"理发","挖掘机"});
        wangxiaoer.setHas_girlfriend(false);
        wangxiaoer.setCar(null);
        wangxiaoer.setHouse(null);
        wangxiaoer.setComment("这是一个注释");
        //print
        System.out.println(new JSONObject(wangxiaoer));
    }

}
